package com.google.code.p.restrpc.http;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.client.RestClientException;

import com.google.code.p.restrpc.util.IOUtils;

public class DefaultResponseErrorHandler implements ResponseErrorHandler {
    
    public boolean hasError(HttpClientResponse response) throws IOException {
        return hasError(response.getStatusCode());
    }
    
    protected boolean hasError(HttpStatus httpStatus) {
        int seriesCode = httpStatus.value() / 100;
        return (seriesCode == 4 || seriesCode == 5);
    }
    
    public void handleError(HttpClientResponse response) throws IOException {
        HttpStatus httpStatus = response.getStatusCode();
        String contentTypeStr = response.getHeaders().getContentType();
        Charset charset = null;
        byte[] body = null;
        if (StringUtils.isNotEmpty(contentTypeStr)) {
            ContentType contentType = ContentType.parse(contentTypeStr);
            charset = contentType != null ? contentType.getCharSet() : null;
            body = getResponseBody(response);
        }
        
        int statusSeriesCode = httpStatus.value() / 100;
        
        switch (statusSeriesCode) {
            case 4:
            case 5:
                throw new HttpClientException(httpStatus, body, charset);
            default:
                throw new RestClientException("Unknown status code [" + httpStatus
                                              + "]");
        }
    }
    
    protected byte[] getResponseBody(HttpClientResponse response) {
        try {
            InputStream responseBody = response.getBody();
            if (responseBody != null) {
                return IOUtils.copyToByteArray(responseBody);
            }
        }
        catch (IOException ex) {
            // ignore
        }
        return new byte[0];
    }
    
}
